package com.jjc.android.fragment

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.graphics.Color
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.allen.library.SuperButton
import com.jjc.android.R
import com.jjc.android.activity.DetectionActivity
import com.jjc.android.activity.InsertCardActivity
import com.jjc.android.base.BaseLazyLoadFragment
import com.jjc.android.dialog.MessageImageDialog
import com.jjc.android.entity.ChangeCardEvent
import com.jjc.android.entity.ChangeDeviceEvent
import com.jjc.android.entity.DetectionBackEvent
import com.jjc.android.entity.ScanCardDto
import com.jjc.android.util.Common.parseFloat
import com.jjc.android.view.BraetheInterpolator
import com.jjc.android.view.count.CountdownView
import com.jjc.android.view.countup.CountupView
import com.jjc.android.view.onClick
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.math.roundToLong

class SamplingCountDownFragment : BaseLazyLoadFragment(){

    companion object{
        fun newInstance():SamplingCountDownFragment{
            val fragment = SamplingCountDownFragment()
            fragment.setInflateLazy(true)
            return fragment
        }
    }

    private lateinit var okBtn: TextView
    private lateinit var countDownView: CountdownView
    private lateinit var countDownLableTxt:TextView
    private lateinit var countUpView:CountupView


    override fun getLayoutId(): Int = R.layout.fragment_sampling_countdown

    override fun initView(view: View) {
        super.initView(view)
        initViews(view)
        okBtn.onClick {
            if(countDownView.remainTime>=1000){
                MessageImageDialog.Builder(requireContext())
                    .imageResId(R.mipmap.alert_chaoshi_pic)
                    .content(getString(R.string.time_not_finish_continue_next_txt))
                    .okClick {
                        nextStep()
                    }
                    .build()
                    .show()
            }else{
                nextStep()
            }

        }
    }

    override fun onFragmentResume(firstResume: Boolean) {
        super.onFragmentResume(firstResume)
        if(prepareCountDown){
            startCountDown()
            prepareCountDown = false
        }
    }

    override fun onFragmentPause() {
        super.onFragmentPause()
    }

    private var prepareCountDown = true


    private fun startCountDown(){
        val scanCard = (activity as? DetectionActivity)?.getScanCardInfo()?: ScanCardDto()
        val countDownTime = (scanCard.danmoe2hn6ie3yqu.parseFloat()*60*1000).roundToLong()
        val timeOutPopDialogTime = (scanCard.fbmfxcaqgsgscrsw.parseFloat()*60*1000).roundToLong()
        countDownView.start(countDownTime)
        countDownView.setOnCountdownEndListener {
            countDownView.visibility = View.GONE
            countUpView.visibility = View.VISIBLE
            countUpView.start(100000)
            val updateColor = Color.parseColor("#FF3141")
            countDownLableTxt.text = "超时"
            countDownLableTxt.setTextColor(updateColor)
            startScaleBreathAnimation(true)
        }

//        countUpView.setOnCountdownIntervalListener(1000
//        ) { cv, remainTime ->
//            if(remainTime in timeOutPopDialogTime until (timeOutPopDialogTime+1500L)){
//                MessageImageDialog.Builder(requireContext())
//                    .imageResId(R.mipmap.alert_chaoshi_pic)
//                    .content("等待时间超时，为保证检测数据准确，请更换试剂卡")
//                    .okClick {
//                        resetInitStatus()
//                        prepareCountDown = true
//                        EventBus.getDefault().post(ChangeCardEvent())
//                    }
//                    .build()
//                    .show()
//            }
//        }
    }



    private val animatorSet:AnimatorSet by lazy {
        val scaleX: ObjectAnimator = ObjectAnimator.ofFloat(okBtn, "scaleX", 1f,0.9f, 1f)
        val scaleY: ObjectAnimator = ObjectAnimator.ofFloat(okBtn, "scaleY", 1f,0.9f, 1f)
        scaleX.repeatCount = ValueAnimator.INFINITE
        scaleY.repeatCount = ValueAnimator.INFINITE
        val animatorSet = AnimatorSet()
        animatorSet.playTogether(scaleX, scaleY)
        animatorSet.duration = 1000
        animatorSet.interpolator = AccelerateDecelerateInterpolator()
        animatorSet
    }
    private var isAnimatoStarted = false
    private fun startScaleBreathAnimation(isStart:Boolean = true) {
        if(isStart){
            isAnimatoStarted = true
            animatorSet.start()
        }else{
            if(isAnimatoStarted){
                animatorSet.cancel()
            }
        }

    }

    private fun resetInitStatus(){
        countDownView.setOnCountdownEndListener(null)
        countUpView.setOnCountdownIntervalListener(1000,null)
        countDownView.stop()
        countUpView.stop()
        countDownView.visibility = View.VISIBLE
        countUpView.visibility = View.GONE
        val updateColor = ContextCompat.getColor(requireContext(),R.color.c_831cb5)
        countDownLableTxt.text = getString(R.string.count_down_txt)
        countDownLableTxt.setTextColor(updateColor)
        startScaleBreathAnimation(false)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: DetectionBackEvent){
        resetInitStatus()
        prepareCountDown = true
    }

    override fun isHaveEventBus(): Boolean {
        return true
    }


    private fun nextStep(){
        resetInitStatus()
        (activity as? DetectionActivity)?.nextStep()
    }

    private fun initViews(view: View) {
        countUpView = view.findViewById(R.id.countUpView)
        countDownView = view.findViewById(R.id.countDownView)
        okBtn = view.findViewById(R.id.okBtn)
        countDownLableTxt = view.findViewById(R.id.countDownLableTxt)
    }
}